package com.lej.app_main.unity

import android.graphics.Bitmap
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lej.app_main.R
import com.lej.app_main.databinding.AppmainCompositeDialogBinding
import com.lej.core.dsl.src
import com.lej.core.permission.checkWithReqNoDialog
import com.lej.core.utils.changeQiniuSize
import com.lej.core.utils.extention.BitmapCrop
import com.lej.core.utils.extention.saveToAlbum
import com.lej.core.utils.extention.toast
import com.lej.core.utils.load
import com.lej.dataservice.club.bean.main.unity.MatchResInfo
import com.lej.dataservice.club.data.PengPermissions
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.impl.FullScreenPopupView
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIDrawableHelper
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class CompositeResDialog(private val act: FragmentActivity, private val data: MatchResInfo) :
    FullScreenPopupView(act) {
    override fun getImplLayoutId() = R.layout.appmain_composite_dialog

    override fun initPopupContent() {
        super.initPopupContent()
        val binding =
            AppmainCompositeDialogBinding.bind(centerPopupContainer.findViewById(R.id.root))
        binding.apply {
            ivClose.onClick { dismiss() }
            ivShare.onClick {
                act.lifecycleScope.launch {
                    val hasPermission = PengPermissions.store.checkWithReqNoDialog(act)
                    if (!hasPermission) return@launch

                    kotlin.runCatching {
                        ivClose.isVisible = false
                        ivShare.isVisible = false
                        val bmp = clRoot.getBitmap() //获取View的副本，就是这个View上面所显示的任何内容
                        val roundBmp = BitmapCrop.fillet(bmp, 32)
                        roundBmp.saveToAlbum(act, getMapName())
                        "图片保存成功".toast()
                        dismiss()
                    }.onFailure { "处理异常".toast() }
                }
            }

            ivLeftConstellation.src = data.left.ariesById
            ivRightConstellation.src = data.right.ariesById
            tvMatchScore.text = "${data.score}分"
            tvMatchTips.text = data.content ?: ""

            data.rewards.let {
                it.getOrNull(0)?.let { award ->
                    ivAwardCover1.load(award.url?.changeQiniuSize(200, 200))
                    tvAwardTitle1.text = award.name ?: ""
                } ?: run {
                    ivAwardCover1.src = R.drawable.icon_match_not_award
                    tvAwardTitle1.text = "谢谢参与！"
                }
                it.getOrNull(1)?.let { award ->
                    ivAwardCover2.load(award.url?.changeQiniuSize(200, 200))
                    tvAwardTitle2.text = award.name ?: ""
                } ?: run {
                    ivAwardCover2.isVisible = false
                    tvAwardTitle2.isVisible = false
                }
                it.getOrNull(2)?.let { award ->
                    ivAwardCover3.load(award.url?.changeQiniuSize(200, 200))
                    tvAwardTitle3.text = award.name ?: ""
                } ?: run {
                    ivAwardCover3.isVisible = false
                    tvAwardTitle3.isVisible = false
                }
            }
        }
    }

    private fun getMapName() = "dayou_${
        SimpleDateFormat(
            "yyMMdd_HHmmssSS",
            Locale.CHINA
        ).format(System.currentTimeMillis())
    }.png"

    companion object {
        fun show(context: FragmentActivity, data: MatchResInfo): BasePopupView =
            XPopup.Builder(context)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .hasStatusBar(false)
                .dismissOnTouchOutside(true)
                .dismissOnBackPressed(true)
                .asCustom(CompositeResDialog(context, data))
                .show()
    }

    private fun View.getBitmap(): Bitmap {
        return QMUIDrawableHelper.createBitmapFromView(this)

//        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
//            draw(Canvas(this)) //使用bitmap构建一个Canvas，绘制的所有内容都是绘制在此Bitmap上的
//        }
//        return bitmap
    }

    private val Int.ariesById
        get() = when (this) {
            1 -> R.drawable.ic_aries_1
            2 -> R.drawable.ic_aries_2
            3 -> R.drawable.ic_aries_3
            4 -> R.drawable.ic_aries_4
            5 -> R.drawable.ic_aries_5
            6 -> R.drawable.ic_aries_6
            7 -> R.drawable.ic_aries_7
            8 -> R.drawable.ic_aries_8
            9 -> R.drawable.ic_aries_9
            10 -> R.drawable.ic_aries_10
            11 -> R.drawable.ic_aries_11
            12 -> R.drawable.ic_aries_12
            else -> R.drawable.ic_aries_1
        }
}